<template>
  <div class="space-y-6">
    <!-- 页面标题和操作 -->
    <div class="flex items-center justify-between">
      <div>
        <h1 class="text-2xl font-bold text-gray-900">申请管理</h1>
        <p class="text-gray-600 mt-1">管理车辆使用申请和审批流程</p>
      </div>
      <el-button type="primary" :icon="Plus" @click="showNewApplicationDialog = true">
        新建申请
      </el-button>
    </div>
    
    <!-- 筛选和搜索 -->
    <el-card>
      <div class="grid grid-cols-1 md:grid-cols-5 gap-4">
        <el-input
          v-model="searchQuery"
          placeholder="搜索申请人或用途"
          :prefix-icon="Search"
          clearable
        />
        <el-select v-model="statusFilter" placeholder="申请状态" clearable>
          <el-option label="待审批" value="pending" />
          <el-option label="已批准" value="approved" />
          <el-option label="已拒绝" value="rejected" />
          <el-option label="使用中" value="in_use" />
          <el-option label="已完成" value="completed" />
        </el-select>
        <el-select v-model="urgencyFilter" placeholder="紧急程度" clearable>
          <el-option label="普通" value="normal" />
          <el-option label="紧急" value="urgent" />
          <el-option label="非常紧急" value="critical" />
        </el-select>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
        <el-button @click="resetFilters">重置筛选</el-button>
      </div>
    </el-card>
    
    <!-- 申请列表 -->
    <el-card>
      <el-table :data="filteredApplications" stripe style="width: 100%">
        <el-table-column prop="id" label="申请编号" width="100" />
        <el-table-column prop="applicant" label="申请人" width="100" />
        <el-table-column prop="department" label="部门" width="120" />
        <el-table-column prop="purpose" label="用途" width="150" show-overflow-tooltip />
        <el-table-column prop="startDate" label="开始时间" width="120" />
        <el-table-column prop="endDate" label="结束时间" width="120" />
        <el-table-column label="紧急程度" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getUrgencyType(row.urgency)"
              size="small"
            >
              {{ getUrgencyText(row.urgency) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              size="small"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assignedVehicle" label="分配车辆" width="120" />
        <el-table-column prop="assignedDriver" label="分配驾驶员" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewApplication(row)">查看</el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              size="small" 
              type="success" 
              @click="approveApplication(row)"
            >
              审批
            </el-button>
            <el-button 
              v-if="row.status === 'approved'" 
              size="small" 
              type="warning" 
              @click="assignVehicle(row)"
            >
              分配
            </el-button>
            <el-button 
              v-if="row.status === 'in_use'" 
              size="small" 
              type="info" 
              @click="completeApplication(row)"
            >
              完成
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="flex justify-center mt-6">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="applications.length"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>
    
    <!-- 新建申请对话框 -->
    <el-dialog v-model="showNewApplicationDialog" title="新建申请" width="600px">
      <el-form
        ref="applicationFormRef"
        :model="applicationForm"
        :rules="applicationRules"
        label-width="100px"
      >
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <el-form-item label="申请人" prop="applicant">
            <el-input v-model="applicationForm.applicant" placeholder="请输入申请人姓名" />
          </el-form-item>
          <el-form-item label="部门" prop="department">
            <el-select v-model="applicationForm.department" placeholder="选择部门" class="w-full">
              <el-option label="行政部" value="行政部" />
              <el-option label="销售部" value="销售部" />
              <el-option label="技术部" value="技术部" />
              <el-option label="财务部" value="财务部" />
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间" prop="startDate">
            <el-date-picker
              v-model="applicationForm.startDate"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm"
              class="w-full"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="endDate">
            <el-date-picker
              v-model="applicationForm.endDate"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm"
              class="w-full"
            />
          </el-form-item>
          <el-form-item label="紧急程度" prop="urgency">
            <el-select v-model="applicationForm.urgency" placeholder="选择紧急程度" class="w-full">
              <el-option label="普通" value="normal" />
              <el-option label="紧急" value="urgent" />
              <el-option label="非常紧急" value="critical" />
            </el-select>
          </el-form-item>
          <el-form-item label="预计里程" prop="estimatedMileage">
            <el-input-number v-model="applicationForm.estimatedMileage" :min="0" class="w-full" />
          </el-form-item>
        </div>
        <el-form-item label="用途" prop="purpose">
          <el-input
            v-model="applicationForm.purpose"
            type="textarea"
            :rows="3"
            placeholder="请详细描述用车用途"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="applicationForm.notes"
            type="textarea"
            :rows="2"
            placeholder="其他备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelNewApplication">取消</el-button>
        <el-button type="primary" @click="submitApplication">提交申请</el-button>
      </template>
    </el-dialog>
    
    <!-- 申请详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="申请详情" width="800px">
      <div v-if="selectedApplication" class="space-y-6">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div class="space-y-4">
            <h3 class="text-lg font-medium text-gray-900">申请信息</h3>
            <div class="bg-gray-50 p-4 rounded-lg space-y-2">
              <div class="flex justify-between">
                <span class="text-gray-600">申请编号:</span>
                <span class="font-medium">{{ selectedApplication.id }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">申请人:</span>
                <span class="font-medium">{{ selectedApplication.applicant }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">部门:</span>
                <span class="font-medium">{{ selectedApplication.department }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">申请时间:</span>
                <span class="font-medium">{{ selectedApplication.createdAt }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">紧急程度:</span>
                <el-tag :type="getUrgencyType(selectedApplication.urgency)" size="small">
                  {{ getUrgencyText(selectedApplication.urgency) }}
                </el-tag>
              </div>
            </div>
          </div>
          <div class="space-y-4">
            <h3 class="text-lg font-medium text-gray-900">使用信息</h3>
            <div class="bg-gray-50 p-4 rounded-lg space-y-2">
              <div class="flex justify-between">
                <span class="text-gray-600">开始时间:</span>
                <span class="font-medium">{{ selectedApplication.startDate }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">结束时间:</span>
                <span class="font-medium">{{ selectedApplication.endDate }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">预计里程:</span>
                <span class="font-medium">{{ selectedApplication.estimatedMileage }} km</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">分配车辆:</span>
                <span class="font-medium">{{ selectedApplication.assignedVehicle || '未分配' }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-gray-600">分配驾驶员:</span>
                <span class="font-medium">{{ selectedApplication.assignedDriver || '未分配' }}</span>
              </div>
            </div>
          </div>
        </div>
        <div>
          <h3 class="text-lg font-medium text-gray-900 mb-2">用途说明</h3>
          <div class="bg-gray-50 p-4 rounded-lg">
            <p class="text-gray-700">{{ selectedApplication.purpose }}</p>
          </div>
        </div>
        <div v-if="selectedApplication.notes">
          <h3 class="text-lg font-medium text-gray-900 mb-2">备注</h3>
          <div class="bg-gray-50 p-4 rounded-lg">
            <p class="text-gray-700">{{ selectedApplication.notes }}</p>
          </div>
        </div>
        <div class="flex justify-between items-center pt-4 border-t">
          <div class="flex items-center space-x-2">
            <span class="text-gray-600">当前状态:</span>
            <el-tag :type="getStatusType(selectedApplication.status)">
              {{ getStatusText(selectedApplication.status) }}
            </el-tag>
          </div>
          <div class="space-x-2">
            <el-button 
              v-if="selectedApplication.status === 'pending'" 
              type="success" 
              @click="approveApplication(selectedApplication)"
            >
              批准申请
            </el-button>
            <el-button 
              v-if="selectedApplication.status === 'pending'" 
              type="danger" 
              @click="rejectApplication(selectedApplication)"
            >
              拒绝申请
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
    
    <!-- 分配车辆对话框 -->
    <el-dialog v-model="showAssignDialog" title="分配车辆和驾驶员" width="500px">
      <el-form label-width="100px">
        <el-form-item label="选择车辆">
          <el-select v-model="assignForm.vehicleId" placeholder="选择车辆" class="w-full">
            <el-option 
              v-for="vehicle in availableVehicles" 
              :key="vehicle.id" 
              :label="`${vehicle.licensePlate} (${vehicle.brand} ${vehicle.model})`" 
              :value="vehicle.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择驾驶员">
          <el-select v-model="assignForm.driverId" placeholder="选择驾驶员" class="w-full">
            <el-option 
              v-for="driver in availableDrivers" 
              :key="driver.id" 
              :label="`${driver.name} (${driver.licenseType})`" 
              :value="driver.id" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAssignDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmAssign">确认分配</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'

// 接口定义
interface Application {
  id: string
  applicant: string
  department: string
  purpose: string
  startDate: string
  endDate: string
  urgency: 'normal' | 'urgent' | 'critical'
  status: 'pending' | 'approved' | 'rejected' | 'in_use' | 'completed'
  estimatedMileage: number
  assignedVehicle?: string
  assignedDriver?: string
  createdAt: string
  notes?: string
}

// 响应式数据
const showNewApplicationDialog = ref(false)
const showDetailDialog = ref(false)
const showAssignDialog = ref(false)
const selectedApplication = ref<Application | null>(null)
const searchQuery = ref('')
const statusFilter = ref('')
const urgencyFilter = ref('')
const dateRange = ref<[string, string] | null>(null)
const currentPage = ref(1)
const pageSize = ref(10)

// 申请表单
const applicationForm = reactive({
  applicant: '',
  department: '',
  purpose: '',
  startDate: '',
  endDate: '',
  urgency: 'normal' as Application['urgency'],
  estimatedMileage: 0,
  notes: ''
})

// 分配表单
const assignForm = reactive({
  vehicleId: null as number | null,
  driverId: null as number | null
})

// 表单验证规则
const applicationRules = {
  applicant: [{ required: true, message: '请输入申请人姓名', trigger: 'blur' }],
  department: [{ required: true, message: '请选择部门', trigger: 'change' }],
  purpose: [{ required: true, message: '请输入用途', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  urgency: [{ required: true, message: '请选择紧急程度', trigger: 'change' }]
}

// 模拟数据
const applications = ref<Application[]>([
  {
    id: 'APP001',
    applicant: '张三',
    department: '销售部',
    purpose: '客户拜访',
    startDate: '2024-01-25 09:00',
    endDate: '2024-01-25 18:00',
    urgency: 'normal',
    status: 'pending',
    estimatedMileage: 100,
    createdAt: '2024-01-24 14:30'
  },
  {
    id: 'APP002',
    applicant: '李四',
    department: '技术部',
    purpose: '设备维护',
    startDate: '2024-01-26 08:00',
    endDate: '2024-01-26 17:00',
    urgency: 'urgent',
    status: 'approved',
    estimatedMileage: 150,
    assignedVehicle: '京A12345',
    assignedDriver: '王师傅',
    createdAt: '2024-01-24 10:15'
  }
])

const availableVehicles = ref([
  { id: 1, licensePlate: '京A12345', brand: '丰田', model: '凯美瑞' },
  { id: 2, licensePlate: '京B67890', brand: '本田', model: '雅阁' }
])

const availableDrivers = ref([
  { id: 1, name: '王师傅', licenseType: 'C1' },
  { id: 2, name: '李师傅', licenseType: 'B2' }
])

// 计算属性
const filteredApplications = computed(() => {
  let filtered = applications.value
  
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(app => 
      app.applicant.toLowerCase().includes(query) ||
      app.purpose.toLowerCase().includes(query)
    )
  }
  
  if (statusFilter.value) {
    filtered = filtered.filter(app => app.status === statusFilter.value)
  }
  
  if (urgencyFilter.value) {
    filtered = filtered.filter(app => app.urgency === urgencyFilter.value)
  }
  
  return filtered
})

// 方法
const getStatusType = (status: Application['status']) => {
  const types = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    in_use: 'primary',
    completed: 'info'
  }
  return types[status]
}

const getStatusText = (status: Application['status']) => {
  const texts = {
    pending: '待审批',
    approved: '已批准',
    rejected: '已拒绝',
    in_use: '使用中',
    completed: '已完成'
  }
  return texts[status]
}

const getUrgencyType = (urgency: Application['urgency']) => {
  const types = {
    normal: '',
    urgent: 'warning',
    critical: 'danger'
  }
  return types[urgency]
}

const getUrgencyText = (urgency: Application['urgency']) => {
  const texts = {
    normal: '普通',
    urgent: '紧急',
    critical: '非常紧急'
  }
  return texts[urgency]
}

const resetFilters = () => {
  searchQuery.value = ''
  statusFilter.value = ''
  urgencyFilter.value = ''
  dateRange.value = null
  ElMessage.success('筛选条件已重置')
}

const viewApplication = (application: Application) => {
  selectedApplication.value = application
  showDetailDialog.value = true
}

const approveApplication = (application: Application) => {
  ElMessageBox.confirm(
    `确定要批准 ${application.applicant} 的申请吗？`,
    '确认批准',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }
  ).then(() => {
    application.status = 'approved'
    ElMessage.success('申请已批准')
    showDetailDialog.value = false
  })
}

const rejectApplication = (application: Application) => {
  ElMessageBox.confirm(
    `确定要拒绝 ${application.applicant} 的申请吗？`,
    '确认拒绝',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    application.status = 'rejected'
    ElMessage.success('申请已拒绝')
    showDetailDialog.value = false
  })
}

const assignVehicle = (application: Application) => {
  selectedApplication.value = application
  showAssignDialog.value = true
}

const confirmAssign = () => {
  if (!assignForm.vehicleId || !assignForm.driverId) {
    ElMessage.warning('请选择车辆和驾驶员')
    return
  }
  
  const vehicle = availableVehicles.value.find(v => v.id === assignForm.vehicleId)
  const driver = availableDrivers.value.find(d => d.id === assignForm.driverId)
  
  if (selectedApplication.value && vehicle && driver) {
    selectedApplication.value.assignedVehicle = vehicle.licensePlate
    selectedApplication.value.assignedDriver = driver.name
    selectedApplication.value.status = 'in_use'
    
    ElMessage.success('车辆和驾驶员分配成功')
    showAssignDialog.value = false
    
    // 重置分配表单
    assignForm.vehicleId = null
    assignForm.driverId = null
  }
}

const completeApplication = (application: Application) => {
  ElMessageBox.confirm(
    `确定要完成 ${application.applicant} 的申请吗？`,
    '确认完成',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    application.status = 'completed'
    ElMessage.success('申请已完成')
  })
}

const submitApplication = () => {
  const newApplication: Application = {
    id: `APP${String(applications.value.length + 1).padStart(3, '0')}`,
    ...applicationForm,
    status: 'pending',
    createdAt: new Date().toLocaleString('zh-CN')
  }
  
  applications.value.unshift(newApplication)
  ElMessage.success('申请提交成功')
  cancelNewApplication()
}

const cancelNewApplication = () => {
  showNewApplicationDialog.value = false
  Object.assign(applicationForm, {
    applicant: '',
    department: '',
    purpose: '',
    startDate: '',
    endDate: '',
    urgency: 'normal',
    estimatedMileage: 0,
    notes: ''
  })
}

// 组件挂载时加载数据
onMounted(() => {
  // 这里可以调用API加载实际数据
})
</script>

<style scoped>
.el-card {
  border-radius: 8px;
}

.el-table {
  border-radius: 8px;
}
</style>